import java.io.File
import java.nio.file.Files

/**
 * 解决markdown图片文件夹迁移问题
 */
fun main() {
    val mover = ImageMover()
    mover.convertMdImageUrl()
    mover.moveResPngs()
}

private fun testRegReplace() {
    val path = """C:\Users\bing\note\Reading\数据结构与算法\数据结构与算法.md"""
    val text = File(path).readText()
    val newText = text.replace("""(!\[.*\])\((res/.*)\)""".toRegex(), """${'$'}1(../${'$'}2)""")
    log(newText)
}

/**
 * 查找目录下的M的文件
 */
fun File.doWithFileExt(ext: String, action: File.() -> Unit) {
    if (!exists() || !isDirectory) throw RuntimeException("不是有效文件夹: $absolutePath")
    listFiles()!!.forEach {
        if (it.name.startsWith(".")) return@forEach
        if (it.isFile && it.extension == ext) {
            log("处理md文件: ${it.absolutePath}")
            it.action()
        } else if (it.isDirectory) {
            it.doWithFileExt(ext, action)
        }
    }
}

fun File.doWithMd(action: File.() -> Unit) {
    doWithFileExt("md", action)
}

fun log(message: String) {
    println(message)
}


class ImageMover {
    private val notePath = """C:\Users\bing\note\"""
    private val noteDir = File(notePath)

    fun convertMdImageUrl() {
        noteDir.doWithFileExt("md") {
            val prefix = calculatePrefix(this)
            val newText = readText().replace("""(!\[.*\])\((res/.*)\)""".toRegex(), """${'$'}1($prefix${'$'}2)""")
            log(newText)
            writeText(newText)
        }
    }

    fun moveResPngs() = movePictures(noteDir)

    private fun movePictures(dir: File) {
        dir.listFiles()!!.forEach {
            if (it.name.startsWith(".") || it.absolutePath == """C:\Users\bing\note\res""") return@forEach
            if (it.isDirectory && it.name == "res") {
                it.listFiles()?.forEach {
                    Files.move(it.toPath(), File("""C:\Users\bing\note\res\${it.name}""").toPath())
                }
                it.delete()
            } else if (it.isDirectory) {
                movePictures(it)
            }
        }
    }

    private fun calculatePrefix(file: File): String {
        val deep = calculateFileDepth(file.absolutePath)
        log("深度：$deep")
        var prefix = ""
        repeat(deep) {
            prefix += "../"
        }
        return prefix
    }

    private fun calculateFileDepth(filePath: String) = filePath.substring(notePath.length).count {
        it == """\""".toCharArray()[0]
    }
}